<template>
  <div class="warpper">

    <div class="cont" style="display: flex;">

      <div class="form" style="width: 30%">
        <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="110px" style="width: 100%;">

          <div style="font-weight: 700;margin-bottom: 20px;margin-top: 20px;">1.Group Info</div>

          <el-form-item label="Group Name" prop="name" style="width:360px">
            <el-input v-model="formData.name" autocomplete="off" placeholder="Group Name" />
          </el-form-item>

          <el-form-item label="Group Code" prop="name" style="width:360px">
            <el-input v-model="formData.groupcode" autocomplete="off" placeholder="Group code" />
          </el-form-item>

          <el-form-item label="Customers" prop="clist" style="width:360px">
            <el-select @change="handleCpyIdSelection" v-model="formData.clistdata" placeholder="Choose Customers"
              style="width:250px" multiple filterable>
              <el-option v-for="item in clist" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="Remark" prop="remark" style="width: 360px;">
            <el-input type="textarea" v-model="formData.remark"></el-input>
          </el-form-item>

          <el-form-item class="tbaat" style="width: 500px;margin-left: 0;">

            <el-table :data="formData.procureditem" prop="procureditem" :cell-style="{'text-align':'center'}"
              :header-cell-style="{'text-align':'center'}" border
              v-if="formData.procureditem && formData.procureditem.length > 0">

              <el-table-column label="Status" prop="status" width="80">
                <template slot-scope="scope">

                  <el-link :underline="false" type="success"
                    v-if="scope.row.status=='Normal'">{{scope.row.status}}</el-link>
                  <el-link :underline="false" type="danger" v-else>{{scope.row.status}}</el-link>

                </template>
              </el-table-column>

              <el-table-column label="Contract">
                <template slot-scope="scope">
                  <el-tag @click="mqindex(scope.$index)" v-if="scope.$index==mqxuanzhongindex"
                    type="success">{{scope.row.startdate}}~{{scope.row.enddate}}</el-tag>
                  <el-tag @click="mqindex(scope.$index)" type="info"
                    v-else>{{scope.row.startdate}}~{{scope.row.enddate}}</el-tag>
                </template>
              </el-table-column>

              <el-table-column label="Operate" width="180">
                <template slot-scope="scope">
                  <el-button @click="savestatus(scope.row,scope.$index)" v-permission="['groupcontracts.update']"
                    size="mini" v-if="isEdit">Expired</el-button>
                  <el-button type="danger" v-permission="['groupcontracts.destroy']" @click="removeItem(scope.row)"
                    size="mini">Del</el-button>
                </template>
              </el-table-column>

            </el-table>
          </el-form-item>


          <el-form-item label="Contract" prop="contract">
            <el-date-picker style="width: 300px;" v-model="contract" type="datetimerange" range-separator="-"
              start-placeholder="Select Start Date" end-placeholder="Select End Date" format="MM-dd-yyyy"
              value-format="MM-dd-yyyy">
            </el-date-picker>
            <el-button type="primary" @click="addItem" :disabled="isaddv">Add</el-button>
          </el-form-item>

        </el-form>
      </div>

      <div class="table" style="width: 70%">
        <div style="font-weight: 700;margin-bottom: 20px;">2.Product List</div>
        <el-button type="primary" plain @click="productadd">Add product</el-button>
        <el-table :data="productdata" size="small" stripe border style="margin-top: 20px;">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="name" label="Name" width="160" align="center" />
          <el-table-column label="Spec" width="100" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Category" width="200" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.category_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Price(S$)" align="center">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.cprice" :min="1" label="Price(S$)" style="width: 65%;"
                placeholder="Enter Price"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="Common Price" width="120" align="center" />
          <el-table-column label="Actions" width="200">
            <template slot-scope="scope">
              <el-button plain @click="delrow(scope.row)">del</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save('ruleForm')" style="margin-left: 170px;">Submit</el-button>
    </div>

    <div class="form">
      <el-dialog title="Add Product" :visible.sync="dialogFormVisible" :close-on-click-modal="false"
        customClass="customWidth" width="70%">
        <div class="toolbar">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="100px"
            label-position="right">
            <el-form-item label="Name">
              <el-input v-model="searchForm.name" @keyup.enter.native="search" placeholder="Enter Name">
              </el-input>
            </el-form-item>

            <el-form-item label="Category" prop="category_id" style="width: 360px;">
              <treeselect v-model="searchForm.category_id" :options="deptOptions" :normalizer="normalizer"
                placeholder="Select Category" style="width: 250px;" @open="onOpen" @close="onClose" />
            </el-form-item>

            <el-form-item>
              <el-button @click="find()" plain>Search</el-button>
              <el-button plain :disabled="multiplev" @click="handleadd">Batch Add
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table" style="width: 100%">
          <el-table :data="tableData" size="small" stripe border style="margin-top: 20px;"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" :selectable="isRowSelectable" />
            <el-table-column prop="name" label="Name" width="160" align="center" />
            <el-table-column label="Spec" width="100" align="center">
              <template v-slot="scope">
                <span>{{ scope.row.uom }}{{ scope.row.uom_sku }}</span>
              </template>
            </el-table-column>
            <el-table-column label="Category" width="200" align="center">
              <template v-slot="scope">
                <span>{{ scope.row.category_name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="Price(S$)" align="center">
              <template v-slot="scope">
                <el-input-number v-model="scope.row.cprice" label="Price(S$)" style="width: 65%;"
                  placeholder="Enter Price"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="Common Price" width="120" align="center" />
            <el-table-column label="Actions" width="200">
              <template slot-scope="scope">
                <el-button plain @click="addv(scope.row,scope.row.id)"
                  :disabled="isDisabled(scope.row.id)">add</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="page">
          <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
            :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
            @current-change="currentChange" />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {
    index as cindex,
  } from "@/api/customer";
  import {
    index as cateindex,
  } from "@/api/product_category";
  import {
    show,
    index,
    update,
    store
  } from "@/api/customer_group";
  export default {
    name: "customer_group",
    mixins: [CURD],
    components: {
      Treeselect
    },
    data() {
      return {
        isaddv: false,
        categories: [],
        deptOptions: [],
        page: {
          total: null,
          per_page: 10,
          sizes: [10, 20, 25, 50],
          current_page: 1
        },
        rules: {},
        title: "",
        cmdTitle: "",
        uploadVisible: false,
        searchForm: {},
        isPaginate: false,
        dialogFormVisible: false,
        productdata: [],
        currency: [{
          id: 1,
          name: "sgd",
        }, {
          id: 2,
          name: "usd",
        }],
        multiplev: false,
        id: null,
        isEdit: false,
        isNew: false,
        formData: {
          procureditem: [],
        },
        module: "customer_group",
        newTitle: "New customer_group",
        editTitle: "Edit customer_group",
        contract: [],
        clist: [],
        xiabiao: -1,
        mqxuanzhongindex: 0,
        oidlist: []
      };
    },
    async created() {
      try {
        const {
          data
        } = await cindex(1, 100); // 假设index是一个异步函数
        this.clist = data;
      } catch (error) {
        console.error('Failed to fetch group:', error);
      }

      this.id = this.$route.query.id
      if (this.id > 0) {
        this.isEdit = true
        const {
          data
        } = await show(this.id);
        this.formData = data;
        let aadaf = await cindex(1, 100, {
          group_id: this.id
        });
        var isbbb = [];
        var issp = aadaf.data;
        for (let is = 0; is < issp.length; is++) {
          isbbb.push(parseInt(issp[is].id));
        }
        this.formData.clistdata = isbbb;
        this.productdata = this.formData.procureditem[0].productlist
        for (var iv = 0; iv < this.productdata.length; iv++) {
          console.log(this.productdata[iv].product_id)
          this.oidlist.push(this.productdata[iv].product_id)
        }

      } else {
        this.isNew = true
      }

      try {
        const {
          data
        } = await cateindex(1, 100); // 假设index是一个异步函数
        this.categories = data;
        // 调用handleTree方法处理数据
        this.deptOptions = this.handleTree(data, "id", "parent_id");
      } catch (error) {
        console.error('Failed to fetch categories:', error);
      }
    },
    methods: {
      isRowSelectable(row, selected) {
        // 返回 false 以禁用选择功能
        return !this.oidlist.includes(row.id);
      },
      isDisabled(id) {
        return this.oidlist.includes(id);
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.multiplev = !selection.length
      },
      goiscustomersku() {
        var isaar = false;
        for (var i = 0; i < this.ids.length; i++) {
          var pid = this.ids[i]
          for (var iv = 0; iv < this.tableData.length; iv++) {
            if (this.tableData[iv].id == pid) {
              if (this.tableData[iv].cprice) {
                console.log(this.tableData[iv].cprice, "ddddddddddddddddd")
              } else {
                console.log(this.tableData[iv].cprice, "eeeeeeeeeeeeeeeee")
                isaar = true;
                return isaar;
              }
            }
          }
        }
        return isaar;
      },
      handleadd() {
        if (this.goiscustomersku()) {
          this.$message.error("Please Enter Price")
          return
        }
        for (var i = 0; i < this.ids.length; i++) {
          var pid = this.ids[i]
          for (var iv = 0; iv < this.tableData.length; iv++) {
            if (this.tableData[iv].id == pid) {
              if (this.oidlist.includes(pid)) {

              } else {
                this.oidlist.push(pid)
                this.tableData[iv].pid = pid
                this.tableData[iv].id = null
                this.productdata.push(this.tableData[iv])
              }
              break
            }
          }
        }
      },
      handleCpyIdSelection() {
        this.$forceUpdate()
      },
      async fetchData() {
        let {
          index
        } = require(`@/api/product`);
        const res = await index(
          this.page.current_page,
          this.page.per_page,
          this.searchForm
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data;
        } else {
          this.tableData = res.data;
        }
        console.log(res.meta)
        if (res.meta) {
          this.isPaginate = true;
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      normalizer(node) {
        if (node.children && node.children.length === 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      handleTree(data, id, parentId, children) {
        let config = {
          id: id || 'id',
          parentId: parentId || 'parentId',
          childrenList: children || 'children'
        };

        var childrenListMap = {};
        var nodeIds = {};
        var tree = [];

        for (let d of data) {
          let parentId = d[config.parentId];
          if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
          }
          nodeIds[d[config.id]] = d;
          childrenListMap[parentId].push(d);
        }

        for (let d of data) {
          let parentId = d[config.parentId];
          if (nodeIds[parentId] == null) {
            tree.push(d);
          }
        }

        for (let t of tree) {
          adaptToChildrenList(t);
        }

        function adaptToChildrenList(o) {
          if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
          }
          if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
              adaptToChildrenList(c);
            }
          }
        }
        return tree;
      },
      productadd() {
        this.fetchData()
        this.dialogFormVisible = true
      },
      addItem() { //增加行
        if (this.contract.length > 0) {
          for (var i = 0; i < this.formData.procureditem.length; i++) {
            var tm = this.formData.procureditem[i].startdate
            if (tm == this.contract[0]) {
              this.$message.error("Please choose a different time");
              return false
            }
          }
          this.xiabiao += 1
          this.formData.procureditem.push({
            index: this.xiabiao,
            status: "Normal",
            del: false,
            productlist: [],
            startdate: this.contract[0],
            enddate: this.contract[1],
          });
          this.isaddv = true
          //this.mqxuanzhongindex = this.formData.procureditem.length - 1;
          this.mqindex(this.mqxuanzhongindex)
        } else {
          this.$message.error("Please select a time")
        }
      },
      mqindex(index) {
        if (this.productdata.length > 0) {
          console.log("aaaaaaaaaaaaaaaaaaaaaaa", this.mqxuanzhongindex, index)
          this.formData.procureditem[this.mqxuanzhongindex].productlist = this.productdata
          this.mqxuanzhongindex = index;
          this.productdata = []
          this.oidlist = []
          console.log("bbbbbbbbbbbbbbbbbbbbbbbbbb", this.mqxuanzhongindex, index)
          this.productdata = this.formData.procureditem[index].productlist
          for (var iv = 0; iv < this.productdata.length; iv++) {
            console.log(this.productdata[iv].product_id)
            this.oidlist.push(this.productdata[iv].product_id)
          }
        } else {
          this.$message.error("Please select a product")
        }
      },
      addv(row, oid) {
        if (row.cprice) {
          if (this.oidlist.includes(oid)) {
            this.$message.error("The product has been added !")
          } else {
            this.oidlist.push(oid)
            row.pid = row.id
            row.id = null
            this.productdata.push(row)
          }
        } else {
          this.$message.error("Please Enter Price")
        }
      },
      async delrow(row) {
        console.log(row, "delrow")
        if (row.id) {
          let data = {
            id: row.id,
            action: "delgroupcontartsproductsbyid"
          };
          await update(data);
        }
        const index = this.productdata.indexOf(row)
        this.productdata.splice(index, 1);
      },
      async removeItem(row) {
        const index = this.formData.procureditem.indexOf(row)
        if (this.formData.procureditem.length > 1) {
          if (this.formData.procureditem[index].id > 0) {
            console.log(row, "removeItem")
            if (row.id) {
              let data = {
                id: row.id,
                action: "delgroupcontractsbyid"
              };
              await update(data);
            }
          }
          this.formData.procureditem.splice(index, 1);
        } else {
          this.$message.error("Keep at least one row of data!")
        }
      },
      savestatus(row, index) {
        this.formData.procureditem[index].status = "Expired"
      },
      onOpen(id) { // 展开
        this.currentOpen = id;
      },
      onClose(id) { // 关闭
        if (this.currentOpen === id) {
          this.currentOpen = null;
        }
      },
      async save(form) {

        this.$refs[form].validate(async (valid) => {
          if (valid) {
            try {
              if (this.productdata.length > 0) {
                this.formData.procureditem[this.mqxuanzhongindex].productlist = this.productdata
              } else {
                this.$message.error("Please select a product")
                return false;
              }
              this.formData.clist = this.formData.clistdata;

              if (this.isEdit) {
                let {
                  update
                } = require(`@/api/${this.module}`);
                let {
                  info
                } = await update(this.formData);
                this.$message.success("Edit successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/customer/customer_group',
                  })
                }, 800);
                const {
                  data
                } = await show(this.id);
                this.formData = data;
                let aadaf = await cindex(1, 100, {
                  group_id: this.id
                });
                var isbbb = [];
                var issp = aadaf.data;
                for (let is = 0; is < issp.length; is++) {
                  isbbb.push(parseInt(issp[is].id));
                }
                this.formData.clistdata = isbbb;

              }
              if (this.isNew) {
                if (this.formData.procureditem != null && this.formData.procureditem.length > 0) {

                } else {
                  this.$message.error("Please add a date");
                  return false
                }
                let {
                  store
                } = require(`@/api/${this.module}`);

                let {
                  info
                } = await store(this.formData);
                this.$message.success("Add successfully");
                setTimeout(() => {
                  this.$store.dispatch('tagsView/delView', this.$route);
                  this.$router.push({
                    path: '/customer/customer_group',
                  })
                }, 800);
              }
              //this.fetchData();
              //this.isEdit = false;
              //this.isNew = false;
            } catch (error) {
              let result = error.response.data;
              this.$message.error(result.info);
            }
          } else {
            this.$message.error("Data verification error, please input according to the specified rules");
            return false;
          }
        });
      }
    }
  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .form .el-tag.el-tag--info {
    display: block;
    width: 100%;
  }

  .tbaat .el-form-item__content {
    margin-left: 0 !important;
  }

  .warpper {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
  }

  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>